package org.example3;

import org.example.Person;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

public class ClientStream {

//    static Person sendObj = new Person("scy");
    static String sendObj = "我是客户端,Abc123";

    public static void main(String[] args) throws Exception{

        Socket socket = new Socket("localhost", 9999);

        OutputStream outputStream = socket.getOutputStream();
        byte[] bytes = SerializerUtil.serialize2ByteArray(sendObj);
        outputStream.write(bytes);
        outputStream.flush();

//        socket.shutdownOutput();

        System.out.println("-------------已发送完成,开始接收------------");


        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream inputStream = socket.getInputStream(); // 这里不阻塞
        byte[] buffer = new byte[4];
        int len=0;
        System.out.println("---------准备读取了----------");
        while ((len = inputStream.read(buffer)) != -1) {
            System.out.println("---------进来了");
            baos.write(buffer, 0, len);
            baos.flush();
        }
        System.out.println("-----------------出来了");
        byte[] bytes1 = baos.toByteArray();
        Object object = SerializerUtil.deserialize2Object(bytes1);
        System.out.println("服务器发送的结果是:" + object + "---类型是:" + object.getClass().getName());

        TimeUnit.SECONDS.sleep(5);
//        socket.close();
        System.out.println("-----socket close执行了,最后一步-----");
        while (true) {

        }

    }
}
